//
//  ACAutoPersist.m
//  ACFramework
//
//  Created by caoyq on 2018/7/18.
//

#import "ACAutoPersist.h"

@interface ACAutoPersist()

/** 当前存放的路径 */
@property (nonatomic, strong) NSString *persistPath;
/** 对应路径下存放的文件（以字典存放） */
@property (nonatomic, strong) NSMutableDictionary *dict;

@end

@implementation ACAutoPersist

- (instancetype)initWithPersistPath: (NSString *)path fileName: (NSString *)fileName
{
    self = [super init];
    if (self) {
        if (![[NSFileManager defaultManager] fileExistsAtPath:path]) {
            [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
        }
        _persistPath = [path stringByAppendingPathComponent:fileName];
        _dict = [NSKeyedUnarchiver unarchiveObjectWithFile:_persistPath];
        if (_dict == nil) {
            _dict = [NSMutableDictionary dictionary];
        }
    }
    return self;
}

#pragma mark - private

///数据保存
- (void)save
{
    NSMutableDictionary *save;
    @synchronized(self)
    {
        if (_persistPath == nil) {
            return;
        }
        save = [_dict mutableCopy];
    }
    [NSKeyedArchiver archiveRootObject:save toFile:_persistPath];
}

#pragma mark - 修改

- (void)setObject: (id)anObject forKey:(nonnull id<NSCopying>)aKey
{
    @synchronized(self)
    {
        if (anObject) {
            [_dict setObject:anObject forKey:aKey];
        }else {
            [_dict removeObjectForKey:aKey];
        }
        [self save];
    }
}

- (void)removeObjectForKey: (id)aKey
{
    @synchronized(self)
    {
        [_dict removeObjectForKey:aKey];
        [self save];
    }
}

- (void)removeObjectsForKeys: (NSArray *)keyArray
{
    @synchronized(self)
    {
        [_dict removeObjectsForKeys:keyArray];
        [self save];
    }
}

- (void)removeAllObjects
{
    @synchronized(self)
    {
        [_dict removeAllObjects];
        [self save];
    }
}

#pragma mark - 读取

- (NSUInteger)count
{
    @synchronized(self)
    {
        return [_dict count];
    }
}

- (id)objectForKey:(id)aKey
{
    @synchronized(self)
    {
        return [_dict objectForKey:aKey];
    }
}

- (NSArray *)allKeysForObject:(id)anObject
{
    @synchronized(self)
    {
        return [_dict allKeysForObject:anObject];
    }
}

- (NSArray*)allKeys
{
    @synchronized(self)
    {
        return [_dict allKeys];
    }
}

- (NSArray*)allValues
{
    @synchronized(self)
    {
        return [_dict allValues];
    }
}

@end
